package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.RedisMessageConstant;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 1.发送短信验证码给手机
     * 2.将验证码存储到redis10分钟
     * 3.redis中的key需要区分是短信验证还是预约成功的key
     * 4.为保证其独一性，用电话号码+短信类型code作为redis的key
     *
     * @param telephone
     * @return
     */
    @RequestMapping("sendToTelephone")
    public Result sendToTelephone(@RequestParam("telephone") String telephone) {
        try {
            Integer valiCode = ValidateCodeUtils.generateValidateCode(6);
            String key = telephone + RedisMessageConstant.SENDTYPE_ORDER;
            jedisPool.getResource().setex(key, 60 * 5, valiCode.toString());
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, valiCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 1.发送短信验证码给手机
     * 2.将验证码存储到redis10分钟
     * 3.redis中的key需要区分是短信验证还是预约成功的key
     * 4.为保证其独一性，用短信类型+电话号码code作为redis的key
     *
     * @param telephone
     * @return
     */
    @RequestMapping("sendTOLogin")
    public Result sendTOLogin(@RequestParam("telephone") String telephone) {
        try {
            Integer valiCode = ValidateCodeUtils.generateValidateCode(4);
            String key = telephone + RedisMessageConstant.SENDTYPE_LOGIN;
            jedisPool.getResource().setex(key, 60 * 5, valiCode.toString());
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, valiCode.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 生成一个带验证码的图片给前端
     * @param response
     * @throws Exception
     */
    @RequestMapping("checkImg")
    public void checkImg(HttpServletResponse response) throws Exception {
        //生成图片
        //1.高和宽
        int height = 30;
        int width = 60;
        String data = "0123456789";
        Random random = new Random();
        //2.创建一个图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //3.获得画板
        Graphics g = image.getGraphics();
        //4.填充一个矩形
        //设置颜色
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.WHITE);
        g.fillRect(1, 1, width - 2, height - 2);
        //设置字体
        g.setFont(new Font("宋体", Font.BOLD | Font.ITALIC, 25));
        StringBuffer sb = new StringBuffer();
        //5.写随机字
        for (int i = 0; i < 4; i++) {
            //设置颜色--随机数
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));

            //获得随机字
            int index = random.nextInt(data.length());
            String str = data.substring(index, index + 1);
            //写入
            g.drawString(str, width / 6 * (i + 1), 20);
            sb.append(str);//  获取验证码数据
        }
        // 验证码保存到redis中
        jedisPool.getResource().setex(RedisConstant.ORDERINFO_CHECKIMG_CODE,60*10,sb.toString());
        //6.干扰线
        for (int i = 0; i < 3; i++) {
            // 设置颜色--随机数
            g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            // 随机绘制先
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
            // 随机点
            g.drawOval(random.nextInt(width), random.nextInt(height), 2, 2);
        }
        // 7.将图片响应给浏览器
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    /**
     *
     * 返回验证码是否正确
     * @param checkCode
     * @return
     */
    @RequestMapping("CheckCode")
    public Result CheckCode(@RequestParam("checkCode")String checkCode) {
        try {
            String redisCheckCode = jedisPool.getResource().get(RedisConstant.ORDERINFO_CHECKIMG_CODE);
            if (null == redisCheckCode) {
                return new Result(false, "验证码已过期");
            }
            jedisPool.getResource().del(RedisConstant.ORDERINFO_CHECKIMG_CODE);
            return new Result(checkCode.equals(redisCheckCode), "验证码");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "验证码不正确");
        }
    }


}
